//
//  GroupInfoViewController.m
//  SportSocial
//
//  Created by yull on 15/1/12.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "GroupInfoViewController.h"
#import "GroupInfoTopCell.h"
#import "PlaceInfoAddressPhoneCell.h"
#import "GroupActivity.h"
#import "GroupInfoActivityCell.h"
#import "GroupNet.h"
#import "ActivityNet.h"
#import "ChatViewController.h"
#import "GroupMsgSender.h"
#import "UIScrollView+PullToRefresh.h"
#import "NDRefreshLoadMoreContainView.h"

@interface GroupInfoViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *infoTableView;

@property (nonatomic, strong) NearGroup *group;
@property (nonatomic, strong) NSMutableArray *activityArray;

@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger totalPage;

@end

@implementation GroupInfoViewController

- (instancetype)initWithNearGroup:(NearGroup *)group
{
    if (self = [super init]) {
        self.group = group;
    }
    return self;
}

- (void)viewDidLoad
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initNavibar];
    
    CGRect rect = CGRectMake(0, 0, self.view.width, self.view.height);
    self.infoTableView = [[UITableView alloc] initWithFrame:rect];
    self.infoTableView.dataSource = self;
    self.infoTableView.delegate = self;
    [self.view addSubview:self.infoTableView];
    
    self.infoTableView.tableFooterView = [[UIView alloc] init];
    
    [self getActivity];
    
    @weakify(self);
    [self.infoTableView nd_addPullToLoadMoreWithActionHandler:^(id sender) {
        @strongify(self);
        [self getActivity];
    }];
}

- (void)initNavibar
{
    [self addCommonBackButton];
    
    self.navigationItem.title = self.group.name;
    
    UIButton *rightButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton1.frame = CGRectMake(0, 0, 28, 26);
    if ([[CurrentUser shareInstance] isMyGroup:self.group.group_id]) {
        [rightButton1 setImage:[UIImage imageNamed:@"title_groupchats"] forState:UIControlStateNormal];
        [rightButton1 setImage:[UIImage imageNamed:@"title_groupchats_selection"] forState:UIControlStateHighlighted];
        [rightButton1 addTarget:self action:@selector(onChat:) forControlEvents:UIControlEventTouchUpInside];
    } else {
        [rightButton1 setImage:[UIImage imageNamed:@"title_icon4"] forState:UIControlStateNormal];
        [rightButton1 setImage:[UIImage imageNamed:@"title_icon4_selection"] forState:UIControlStateHighlighted];
        [rightButton1 addTarget:self action:@selector(onAdd:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    UIBarButtonItem *rightItem1 = [[UIBarButtonItem alloc] initWithCustomView:rightButton1];
    
    UIButton *rightButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton2.frame = CGRectMake(0, 0, 28, 26);
    [rightButton2 setImage:[UIImage imageNamed:@"title_collection"] forState:UIControlStateNormal];
    [rightButton2 setImage:[UIImage imageNamed:@"title_collection_selection"] forState:UIControlStateHighlighted];
    [rightButton2 addTarget:self action:@selector(onFollow:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem2 = [[UIBarButtonItem alloc] initWithCustomView:rightButton2];
    
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:rightItem1,rightItem2, nil];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    }
    return self.activityArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            NSString *text = nil;
            if (self.group.remark.length > 0) {
                text = self.group.remark;
            }else {
                text = self.group.name;
            }
            return [GroupInfoTopCell calulateHeightWithText:text];
            
        }else {
            return [PlaceInfoAddressPhoneCell calulateCellHeightWithText:self.group.address];
        }
    }else {
        GroupActivity *activity = [self.activityArray objectAtIndex:indexPath.row];
        
        return [GroupInfoActivityCell calulateCellHeightWithText:activity.content];
    };
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            GroupInfoTopCell *topCell = [tableView dequeueReusableCellWithIdentifier:@"TopCell"];
            if (!topCell) {
                topCell = [[GroupInfoTopCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TopCell"];
                topCell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            [topCell drawCellWithGroup:self.group];
            return topCell;
        } else {
            PlaceInfoAddressPhoneCell *centerCell = [tableView dequeueReusableCellWithIdentifier:@"CeterCell"];
            if (!centerCell) {
                centerCell = [[PlaceInfoAddressPhoneCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CenterCell"];
            }
            if (indexPath.row == 1) {
                [centerCell drawCellWithText:self.group.address];
                centerCell.iconImageView.image = [UIImage imageNamed:@"icon_ad"];
            }
            return centerCell;
        }
        return nil;
    }else {
        GroupInfoActivityCell *activityCell = [tableView dequeueReusableCellWithIdentifier:@"ActivityCell"];
        if (!activityCell) {
            activityCell = [[GroupInfoActivityCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivityCell"];
            activityCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [activityCell drawCellWithActivity:[self.activityArray objectAtIndex:indexPath.row]];
        return activityCell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            NSLog(@"点击了地址");
        }
    }
}

- (void)getActivity
{
    @weakify(self);
    [ActivityNet activityPageWithGroupId:self.group.group_id pageNumber:self.currentPage+1 pageSize:10 successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSArray *dictArray = [[responseObject objectForKey:@"data"] objectForKey:@"list"];
            if (dictArray.count > 0) {
                if (!self.activityArray) {
                    self.activityArray = [NSMutableArray array];
                }
                
                self.currentPage = [[[responseObject objectForKey:@"data"] objectForKey:@"pageNumber"] integerValue];
                self.totalPage = [[[responseObject objectForKey:@"data"] objectForKey:@"totalPage"] integerValue];
                
                for (NSDictionary *dict in dictArray) {
                    [self.activityArray addObject:[GroupActivity groupActivityWithDict:dict]];
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (self.currentPage == self.totalPage) {
                        ((NDRefreshLoadMoreContentView *)(self.infoTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNoMore;
                    } else {
                        ((NDRefreshLoadMoreContentView *)(self.infoTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNormal;
                    }
                    [self.infoTableView nd_endLoadMore];
                    [self.infoTableView reloadData];
                });
                
            }
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

//添加收藏

- (void)onFollow:(id)sender
{
    [self showHUD];
    
    [GroupNet addNoticeGroupWithId:self.group.group_id successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [self hideHUD];
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"收藏成功！" time:2];
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hideHUD];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)onChat:(id)sender
{
    ChatViewController *chatViewController = [[ChatViewController alloc] init];
    chatViewController.msgSender = [[GroupMsgSender alloc] initWithGroup:self.group];
    [self.navigationController pushViewController:chatViewController animated:YES];
}

- (void)onAdd:(id)sender
{
    [self showHUD];
    
    [GroupNet applyWithGroupId:self.group.group_id successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [self hideHUD];
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"申请成功！" time:2];
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [self hideHUD];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

@end
